package com.aaa.threadcommunication;

import javax.swing.plaf.basic.BasicLookAndFeel;

/**
 * @author C-Q
 * @version 1.1.0
 * @Description: TODO
 * @date 2022/11/1
 */
public class Card {
    private double balance;
    //true有钱--false没钱
    private boolean flag=false;


    //存钱方法----方法上加synchronized表示整个方法都加锁了,默认的锁对象就是this
    public synchronized void save(double money){
        //卡中有钱
        if(flag==true){
            try {
                //表示当前线程释放锁并进入等待队列
                wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        balance=balance+money;
        System.out.println(Thread.currentThread().getName()+"存入了"+money+"元, 卡中余额："+balance);
        flag=true;
        //唤醒等待队列中的线程
        notify();

    }

    //取钱
    public synchronized void token(double money){
        //卡中没钱
        if(flag==false){
            try {
                wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        balance=balance-money;
        System.out.println(Thread.currentThread().getName()+"取了"+money+"元, 卡中余额："+balance);
        flag=false;
        //唤醒等待队列中的线程
        notify();
    }
}
